<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :edit-btn="false"
      :page.sync="page"
      :before-open="beforeOpen"
      :column-width="columnWidth"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      :permission="permissionList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <template #status="{row}">
        <el-tag v-if="row.status === 1" size="small" type='warning'>审核中</el-tag>
        <el-tag v-if="row.status === 2" size="small" type="success">审批通过并且未上报</el-tag>
        <el-tag v-if="row.status === 3" size="small" type="danger">审批不通过</el-tag>
        <el-tag v-if="row.status === 4" size="small">已上报</el-tag>
      </template>
      <template
        slot-scope="scope"
        slot="menuLeft">
        <el-button type="primary"
                   icon="el-icon-plus"
                   size="small"
                   v-if="userInfo.role_name.includes('medical')"
                   @click="addForm">新增
        </el-button>
        <el-button
          type="primary"
          size="small"
          plain icon="el-icon-upload2"
          v-if="userInfo.role_name.includes('medical')"
          @click="handleImport">批量导入采购申请
        </el-button>
      </template>
      <template #purchaseItemEntityListForm="data">
        <avue-crud :option="optionSub" :data="data.value">
          <template #status="{row}">
            <el-tag v-if="row.status === 1" size="small" type='warning'>审核中</el-tag>
            <el-tag v-if="row.status === 2" size="small" type="success">审批通过</el-tag>
            <el-tag v-if="row.status === 3" size="small" type="danger">审批不通过</el-tag>
            <el-tag v-if="row.status === 4" size="small" type='warning'>药品有效性待核实</el-tag>
          </template>
          <template
            slot="menuLeft"
            slot-scope="{size}">
            <el-button
              type="primary"
              icon="el-icon-finished"
              v-if="userInfo.role_name.includes('districtAdmin')&&isView"
              @click="$refs.crud.rowUpdate()">全部审批通过
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text" size="small" icon="el-icon-circle-check" @click.stop="handleAudit(scope.row)">审批通过
            </el-button>
            <el-button type="text" size="small" icon="el-icon-circle-close" @click.stop="turnDwn(scope.row)">审批不通过
            </el-button>
          </template>
        </avue-crud>
      </template>
      <template #menu="{row,index,size}">
        <el-button type="text" icon="el-icon-view" :size="size"
                   @click="lookSubForm(row,index,'look')">查看
        </el-button>
        <el-button type="text" icon="el-icon-s-check" :size="size" v-if="userInfo.role_name.includes('districtAdmin')"
                   @click="lookSubForm(row,index,'shenhe')">审核
        </el-button>
        <el-button v-show='[2, 4].includes(row.status)' type="text" icon="el-icon-upload2" :size="size"
                   v-if="userInfo.role_name.includes('districtAdmin')" @click="showUpData(row)">上报
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="数据导入" append-to-body :visible.sync="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter" :upload-before="uploadBefore">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate" plain>
            点击下载模板<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
        <template slot="wrong">
          <div>
            <hr>
          </div>
          <div>
            <el-alert v-if="showExportButton"
                      title="注意，导入数据有部分有错误，点击下载可查看错误消息"
                      type="error"
                      :closable="false"
                      show-icon>
            </el-alert>
            <div>

            </div>
            <el-button type="primary" v-if="showExportButton" @click="handleExport" plain>
              点击下载导入失败数据<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </div>

        </template>
        <template #isCovered>
          <el-alert
            title="注意，重复导入相同药品将覆盖之前的数据"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog title="操作提示" :visible.sync="updataBox" :fullscreen="false" append-to-body center destroy-on-close
               width="500px" height="30px">
      <el-row>
        <el-col :span="3">
          <div style="float:right"><i class="el-icon-warning" style="color: RGB(230,162,60);font-size: 40px"></i></div>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="18">
          <div style="font-size: 16px">药品采购单：<strong
            style="color: #004ca7">{{ medpurPurchase.instName }}（{{ medpurPurchase.month }}）</strong>
            <br>您可以选择：【提交】上报给市级管理部门，或者【撤回】已上报的药品采购单。
          </div>
        </el-col>
        <el-col :span="2"></el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-refresh-left" size="small" type="info" @click="handleSubmitData(medpurPurchase.id,2)">撤 回</el-button>
        <el-button icon="el-icon-finished" size="small" type="primary" @click="handleSubmitData(medpurPurchase.id,4)">提 交</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, updates, save, submit} from "@/api/business/purchase";
import {
  getList as getListSub,
} from "@/api/business/purchaseItem";
import {getOne as one} from "@/api/business/medicine"
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import {exportBlob} from "@/api/common";
import {mapGetters} from "vuex";
import NProgress from "nprogress";
import {dateNow} from "@/util/date";

export default {
  data() {
    return {
      showExportButton: false,
      action: "",
      outTime: '',
      downloadUrl: null, // 保存接口返回文件的下载链接
      isView: true,
      medpurPurchase: {},
      updataBox: false,
      showBtn: true,
      BooleanVariable: false,
      columnWidth: {
        month: '50px',
      },
      excelBox: false,
      auditVisible: false,
      auditData: {},
      subColumns: [], // 子表的列配置
      form: {},
      data: [],
      query: {},
      loading: true,
      selectionList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        // column: 3,
        emptyBtn: false,
        columnBtn: false,
        labelWidth: 130,
        searchLabelWidth: 120,
        dialogMenuPosition: 'right',
        dialogWidth: '80%',
        addBtn: false,  //表格新增按钮
        updateBtn: false,
        editBtn: false,
        cancelBtn: false,
        editTitle: "审核", //表格修改弹窗标题
        editBtnText: "审核", //表格修改按钮文案
        height: 'auto', //
        calcHeight: 60, //表格的高度，默认为自动高度。如果设置为auto，会自适应窗口高度，配合calcHeight参数去调节范围
        tip: false,
        searchShow: true, //表格搜索首次是否展示
        menuTitle: '操作', //操作栏标题
        searchMenuSpan: 6,
        border: true,
        menu: true,
        index: false,
        viewBtn: false,
        selection: false, //是否有选择框
        dialogClickModal: false, //表格弹窗是否可以通过点击modal关闭
        searchShowBtn: false, //表格搜索显隐按钮
        searchIcon: true, //表格搜索半收缩按钮
        searchIndex: 4, //表格搜索半收缩个数
        delBtn: false,//
        column: [
          {
            label: "id",
            prop: "id",
            type: "input",
            addDisplay: false, //表单新增时项是否显示
            editDisplay: false,
            viewDisplay: true,
            hide: true,
            display: false,
          },
          {
            label: "药品流水号",
            prop: "medicineNo",
            type: "input",
            search: false,
            span: 8, // 设置该列的跨度为8，即占据一行的三分之一
            editDisabled: false,
            editDisplay: false,
            viewDisplay: true,
            hide: true,
            change: ({column, value}) => {
              // console.log(column)
              // 调用后端接口查询药品信息
              one(value)
                .then(response => {
                  const data = response.data.data;
                  this.optionSub.column.forEach(item => {
                    if (item.prop !== 'medicineNo'&&item.prop!== 'id') {
                      this.form[item.prop] = data[item.prop]
                    }
                    this.form.price = data.bidPrice;
                    this.form.package = data.packages;
                  })
                })
                .catch(error => {
                  console.error('Failed to fetch medicine data:', error);
                });
            },
            blur: ({column, value}) => {
              function areAllPropertiesEmpty(obj) {
                for (var key in obj) {
                  if (obj.hasOwnProperty(key) && obj[key] !== null && obj[key] !== undefined && obj[key] !== '' && key !== 'medicineNo') {
                    return false;
                  }
                }
                return true;
              }

              if (areAllPropertiesEmpty(this.form) && value !== '') {
                // this.findObject(this.option.column, 'package').disabled = false;
                // this.findObject(this.option.column, 'medicineName').disabled = false;
                // this.findObject(this.option.column, 'package').disabled = false;
                // this.findObject(this.option.column, 'package').disabled = false;
                //this.findObject(this.option.column, 'package').disabled = false;
                // this.findObject(this.option.column, 'package').disabled = false;
                // this.findObject(this.option.column, 'package').disabled = false;
                this.showAlert({
                  message: '暂未获取药品数据，请继续填报完毕，并等待审核！',
                  title: '提示',
                  options: {
                    text: '确认'
                  }
                })
              } else {
                //this.findObject(this.option.column, 'package').disabled = true;
                //this.findObject(this.option.column, 'medicineName').disabled = true;
              }
            },
            rules: [
              {
                required: true,
                message: "请输入药品流水号",
                trigger: "blur",
              }
            ]
          },
          {
            label: "上报月份",
            prop: "month",
            type: "month",
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            span: 6,
            labelWidth: 100,
            addDisplay: true,
            viewDisabled: false,
            viewDisplay: false,
            editDisabled: true,
            editDisplay: true,
            search: true,//搜索
            rules: [{
              required: true,
              message: "请输入上报月份",
              trigger: "blur"
            }],
          },
          {
            label: "上报机构ID",
            prop: "instId",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            addDisplay: false,
            viewDisplay: false,
            editDisabled: true,
            editDisplay: false,
          },
          {
            label: "上报机构编码",
            prop: "instNo",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,

          },
          {
            label: "上报医药机构",
            prop: "instName",
            type: "input",
            hide: false,
            span: 6,
            labelWidth: 100,
            addDisplay: false,
            editDisabled: true,
            viewDisplay: false,
            search: true,//搜索
          },
          {
            label: "上报人姓名",
            prop: "createUserName",
            type: "input",
            viewDisplay: false,
            editDisabled: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "地市",
            prop: "city",
            type: "input",
            hide: true,
            addDisplay: false,
            viewDisplay: false,
            editDisabled: false,
            editDisplay: false,
          },
          {
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            label: "区县",
            prop: "district",
            type: "select",
            addDisplay: false,
            viewDisplay: false,
            editDisabled: false,
            editDisplay: false,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "状态",
            prop: "status",
            type: "select",
            viewDisplay: true,
            addDisplay: false,
            search: true,//搜索
            dicUrl: "/api/blade-system/dict/dictionary?code=procure_report",
            dataType: "string",
            editDisabled: true,
            editDisplay: false,
            props: {
              label: "dictValue",
              value: "dictKey"
            }
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "更新人",
            prop: "updateUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "更新时间",
            prop: "updateTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "删除标识",
            prop: "isDeleted",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "创建人",
            prop: "createUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "创建部门",
            prop: "createDept",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: '明细',
            prop: 'purchaseItemEntityList',
            span: 24, // 设置该列的跨度为8，即占据一行的三分之一
            formslot: true,
            slot: true,
            hide: true,
            addDisplay: false,
          },
          // optionSub
          {
            label: "上报单ID",
            prop: "purchaseId",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            addDisplay: false,
            hide: true,
          },
          {
            label: "通用名",
            prop: "medicineName",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
            // disabled:true,
          },
          {
            label: "挂网类型",
            prop: "publishType",
            type: "select",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            addDisplay: true,
            viewDisplay: false,
            editDisplay: false,
            dicUrl: "/api/blade-system/dict/dictionary?code=hang_net_type",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "剂型",
            prop: "shotType",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "规格",
            prop: "specification",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "包装",
            prop: "package",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
            // disabled: true
          },
          {
            label: "质量类型",
            prop: "qualityType",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "新版基药属性",
            prop: "baseMedProp",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "生产企业注册号",
            prop: "produceCompanyNo",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "生产企业名称",
            prop: "produceCompanyName",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            hide: true,
            editDisplay: false,
          },
          {
            label: "挂网价格",
            prop: "price",
            type: "input",
            viewDisplay: false,
            hide: true, //是否在桌面展示
            editDisplay: false,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            rules: [{
              required: true,
              message: "上报价格为数字",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
          },
          {
            label: "采购价格",
            prop: "actualPrice",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
            rules: [{
              required: true,
              message: "采购价格价为数字",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
          },
          {
            label: "配送数量",
            prop: "amount",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
            rules: [{
              required: true,
              message: "配送数量为数字",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
          },
          {
            label: "是否履行备案手续",
            prop: "fileRecord",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "地市",
            prop: "city",
            type: "input",
            hide: true,
            editDisplay: false,
            addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "采购单名称",
            prop: "purchaseOrderName",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            // addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "医院名称",
            prop: "hospitalName",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "省集采网医院账号",
            prop: "hospitalAccount",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "卫生室名称",
            prop: "clinicName",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "is47",
            prop: "is47",
            type: "input",
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            hide: true,
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "配送企业名称",
            prop: "distributionCompanyName",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "配送企业编号",
            prop: "distributionCompanyNo",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "采购单提交时间",
            prop: "purchaseOrderTime",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "采购金额",
            prop: "purchaseAmount",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "配送时间",
            prop: "deliverTime",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "配送数量",
            prop: "deliverQuantity",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "配送金额",
            prop: "deliverAmount",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "采购单入库时间",
            prop: "purchaseInTime",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "包装单位入库数量",
            prop: "packageQuantity",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "制剂单位入库数量",
            prop: "preparationQuantity",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
          {
            label: "入库金额",
            prop: "warehousingAmount",
            type: "input",
            hide: true,
            span: 6, // 设置该列的跨度为8，即占据一行的三分之一
            editDisplay: false,
            //addDisplay: false,
            viewDisplay: false,
          },
        ]
      },
      subVisible: true,
      direction: 'rtl',
      purchaseId: 0,
      purchaseName: "药品采购上报单",
      formSub: {},
      querySub: {},
      loadingSub: true,
      dataSub: [],
      selectionListSub: [],
      pageSub: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      optionSub: {
        refreshBtn: false,
        menuWidth: 200, //操作栏宽度
        delBtnIcon: "el-icon-circle-close",
        delBtnText: "驳回",
        delBtn: false,
        editBtnIcon: "el-icon-circle-check",
        updateBtnText: "通过",
        editTitle: "审核",
        editBtnText: "审核",
        editBtn: false,
        addBtn: false,
        columnBtn: false,
        menu: true,
        menuBtn: true,
        height: '600',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: false,
        selection: false,
        //dialogWidth:'90%',//弹窗大小
        column: [
          {
            label: "id",
            prop: "id",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "上报单ID",
            prop: "purchaseId",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            addDisplay: false,
            hide: true,
          },
          {
            label: "药品流水号",
            prop: "medicineNo",
            type: "input",
            width: 120,
            search: false,
            editDisabled: false,
            editDisplay: false,
            hide: false,
            viewDisplay: true,
            change: ({column, value}) => {
              // 调用后端接口查询药品信息
              one(value)
                .then(response => {
                  const data = response.data.data;
                  // 填充其他对应字段
                  this.optionSub.column.forEach(item => {
                    // console.log('item',item,data)
                    if (item.prop !== 'medicineNo') {
                      this.form[item.prop] = data[item.prop]
                    }
                  })
                })
                .catch(error => {
                  console.error('Failed to fetch medicine data:', error);
                });
            },
            rules: [
              {
                required: true,
                message: "请输入药品流水号",
                trigger: "blur",
              }
            ]
          },
          {
            label: "上报月份",
            prop: "month",
            type: "month",
            hide: true,
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            viewDisabled: true,
            viewDisplay: false,
            editDisplay: false,
            search: false,
            width: 500
          },
          {
            label: "通用名",
            prop: "medicineName",
            type: "input",
            hide: false,
            width: 200,
            overHidden: true,
          },
          {
            label: "挂网类型",
            prop: "publishType",
            type: "select",
            width: 150,
            overHidden: true,
            hide: false,
            viewDisplay: false,
            editDisplay: false,
            dicUrl: "/api/blade-system/dict/dictionary?code=hang_net_type",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "剂型",
            prop: "shotType",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            hide: false,
          },
          {
            label: "规格",
            prop: "specification",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            hide: false,
          },
          {
            label: "包装",
            prop: "pack",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            hide: false,
          },
          {
            label: "质量类型",
            prop: "qualityType",
            type: "input",
            display: false,
            editDisplay: false,
            hide: false,
            viewDisplay: false,
          },
          {
            label: "新版基药属性",
            prop: "baseMedProp",
            type: "input",
            width: 120,
            // disabled: false,
            hide: false,
            viewDisplay: false,
            editDisplay: false,
            display: false,
          },
          {
            label: "生产企业注册号",
            prop: "produceCompanyNo",
            type: "input",
            display: false,
            hide: true,
            viewDisplay: false,
            editDisplay: false,
          },
          {
            label: "生产企业名称",
            prop: "produceCompanyName",
            type: "input",
            width: 200,
            overHidden: true,
            viewDisplay: false,
            hide: false,
            editDisplay: false,
          },
          {
            label: "价格",
            prop: "price",
            type: "input",
            viewDisplay: false,
            fixed: 'right',
            hide: false,
            editDisplay: false,
            rules: [{
              required: true,
              message: "请输入上报价格",
              trigger: "blur",
              pattern: /^\d+$/,
            }],
          },
          {
            label: "采购价格",
            prop: "actualPrice",
            type: "input",
            fixed: 'right',
            width: 100,
            viewDisplay: false,
            editDisplay: false,
            hide: false,
          },
          {
            label: "配送数量",
            prop: "amount",
            type: "input",
            fixed: 'right',
            viewDisplay: false,
            editDisplay: false,
            hide: false,
          },
          {
            label: "是否履行备案手续",
            prop: "fileRecord",
            type: "input",
            viewDisplay: false,
            editDisplay: false,
            hide: true,
          },
          {
            label: "地市",
            prop: "city",
            type: "input",
            editDisplay: false,
            addDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "区县",
            prop: "district",
            type: "select",
            viewDisplay: false,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "状态",
            prop: "status",
            type: "select",
            addDisplay: false,
            fixed: 'right',
            width: 150,
            editDisabled: false,
            editDisplay: false,
            viewDisplay: false,
            dicUrl: "/api/blade-system/dict/dictionary?code=purchase_item",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "创建人",
            prop: "createUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "更新人",
            prop: "updateUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "更新时间",
            prop: "updateTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "删除标识",
            prop: "isDeleted",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "创建部门",
            prop: "createDept",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          }
        ]
      },
      subData: [],
      excelForm: {},

    };
  },
  created() {
    this.updateAction(); // 初始化时更新 action 值
    let district = this.findObject(this.option.column, 'district');
    let instName = this.findObject(this.option.column, 'instName');
    if (this.userInfo.role_name === "medical") {
      district.searchDisabled = true
      instName.searchDisabled = true
      district.searchValue = this.loginUserInfo.institution.district
      instName.searchValue = this.loginUserInfo.institution.instName
      this.$set(this.query, "instName", instName.searchValue)
      this.$set(this.query, "district", district.searchValue)
    }
    if (this.userInfo.role_name === "districtAdmin") {
      district.searchDisabled = true
      district.searchValue = this.loginUserInfo.dept.remark
      this.$set(this.query, "district", district.searchValue)
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission", "loginUserInfo"]),
    excelOption() {
      return {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '数据上传中，请稍等',
            span: 24,
            showFileList: false,
            tip: '请上传 .xls,.xlsx 标准格式文件，',
            action: `/api/purchase/import-order?outTime=${this.outTime}`,
          },
          {
            label: "",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            span: 24,
            value: 0,
            slot: true,
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,

          },
          {
            label: '',
            prop: 'wrong',
            type: "switch",
            formslot: true,
            span: 24,


          }
        ]
      }
    },
    permissionList() {
      return {

        addBtn: this.vaildData(this.permission.medicine_add, false),
        viewBtn: this.vaildData(this.permission.medicine_view, true),
        delBtn: this.vaildData(this.permission.medicine_delete, false),
        editBtn: this.vaildData(this.permission.medicine_edit, true)
      };

    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    subIds() {
      let ids = [];
      this.selectionListSub.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    updateAction() {
      /// this.excelOption.column.action = `/api/purchase/import-order?outTime=${this.outTime}`;
    },
    handleExport() {
      this.$confirm("是否导出错误数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          // 获取 action 属性的返回值
          // const action = this.excelOption.column[0].action;
          const outTime = this.outTime;

          console.log("-----===-----", outTime);
          //console.log(action); // 输出: "/api/purchase/import-order"
          //const {status} = this.query;

          const params = {outTime};
          // 过滤掉值为 undefined 的条件
          const queryStr = Object.entries(params)
            .filter(([key, val]) => val !== undefined)
            .map(([key, val]) => `${key}=${val}`)
            .join('&');

          const url = `/api/purchase/exportMedicine?${this.website.tokenHeader}=${getToken()}&${queryStr}`;
          NProgress.start();
          exportBlob(url)
            .then(res => {
              downloadXls(res.data, `导入错误数据${dateNow()}.xlsx`);
              NProgress.done();
            });

        }
      );
    },
    lookSubForm(row, index, value) {
      value === 'look' ? this.optionSub.menu = false : this.optionSub.menu = true
      value === 'look' ? this.isView = false : this.isView = true;
      console.log(this.isView)
      this.$refs.crud.rowEdit(row, index, 1)
    },
    showAlert(obj) {
      this.$alert(obj.message, obj.title, {
        confirmButtonText: obj.options.text,
        // callback: action => {
        //   // this.$message({
        //   //   type: 'info',
        //   //   message: `action: ${action}`
        //   // });
        // }
      });
    },
    addForm() {
      // this.option.column = [...this.optionSub.column, ...this.option.column]
      this.$refs.crud.rowAdd()
    },
    handleAudit(row) {
      this.$confirm("确认审批通过数据?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          if (row.status === 4) {
            this.$message({
              type: "warning",
              message: "当前药品为未核实药品,请核实后在审批",
            })
            //throw new Error("未核实药品"); // 抛出一个异常
          } else if (row.status === 2) {
            this.$message({
              type: "warning",
              message: "当前药品已审核请勿重复审核",
            })
          } else {
            row.status = 2;
            return updates(row)
              .then(() => {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });

              });
          }
        })
    },
    turnDwn(row) {
      this.$confirm("确认驳回此数据?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          if (row.status !== 4) {
            row.status = 3;
            return updates(row)
              .then(() => {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              });
          } else {
            this.$message({
              type: "warning",
              message: "当前药品未核实，无法操作!"
            });
          }
        })
    },
    // 主表模块
    rowSave(row, done, loading) {

      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row.purchaseItemEntityList).then((res) => {
        //console.log(row.purchaseItemEntityList)
        console.log(res.data.msg)
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: res.data.msg
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    }
    ,
    handleImport() {
      this.showExportButton = false;
      this.outTime = Date.now();
      //this.updateAction(); // 初始化时更新 action 值
      this.excelForm = {}
      this.excelBox = true;
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    }
    ,
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    beforeOpen(done, type) {
      //console.log('a', type)
      if (type === 'view') {
        this.option.menu = false;
      } else if (type === 'edit') {
        this.option.menu = true;
      }
      if (["view", "edit"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          //console.log("purchaseItemEntityList=", res.data.data)
          // this.formSub = res.data.data.purchaseItemEntityList
        });
      } else {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data;
        // });
      }
      done();//this.option.menu = true;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    }
    ,
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    }
    ,
    selectionChange(list) {
      this.selectionList = list;
    }
    ,
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    }
    ,
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    }
    ,
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    }
    ,
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
    ,

    refreshChange() {
      this.onLoad(this.page, this.query);
    }
    ,
    onLoadSub(page, params = {}) {
      this.loadingSub = true;
      const values = {
        ...params,
        purchaseId: this.purchaseId,
      }
      getListSub(page.currentPage, page.pageSize, Object.assign(values, this.querySub)).then(res => {
        const data = res.data.data;
        // console.log(data, "kkkk")
        this.pageSub.total = data.total;
        this.dataSub = data.records;
        this.selectionListSub = [];
        this.loadingSub = false;
        this.subData = data.records
        // console.log(this.subData)
      });
    },
    handleTemplate() {
      exportBlob(`/api/purchase/export-template?${this.website.tokenHeader
      } = ${getToken()}`).then(res => {
        downloadXls(res.data, "药品采购上报-模板.xlsx");
      })
    },
    uploadBefore(file, done, loading) {
      // this.outTime = Date.now()
      done()
    },
    uploadAfter(res, done, loading, column) {
      console.log(res)
      // this.outTime = Date.now();
      this.showExportButton = res.data === 0;
      try {
        console.log("upload res: ", res.msg, res.data)
        this.$message[res.data === 1 ? 'success' : 'warning'](res.msg);

        this.refreshChange();
      } finally {
        done()
      }
    },
    showUpData(row) {
      this.updataBox = true;
      this.medpurPurchase = row;
    },
    handleSubmitData(id, status) {
      this.medpurPurchase.status = status;
      this.medpurPurchase.id = id;
      let msg = status === 4 ? "提交" : "撤回";
      return submit(this.medpurPurchase).then(res => {
        const data = res.data;
        if (data.success) {
          this.$message.success("采购单【" + msg + "】成功!");
        } else {
          this.$message.error(data.msg || "提交失败");
        }
      }).finally(() => {
        this.updataBox = false;
        this.medpurPurchase = {};
        this.onLoad(this.page);
      });
    }
  }
  ,
}
;


</script>

<style lang="scss" scoped>

</style>
